'use strict';
const Service = require('egg').Service;
class UserService extends Service {
  _userPublicInfo(info) {
    const {
      account,
      nickname,
      phone,
      valid,
      valid_name,
      state,
      photo,
    } = info;
    const res = {
      account,
      nickname,
      phone,
      valid,
      valid_name,
      state,
      photo,
    };
    return res;
  }

  async findByMobile(mobile) {
    const result = await this.app.mysql.get('user', { phone: mobile });
    // console.log(result);
    return result;
  }

  async findPublicbyMobile(mobile) {
    const result = await this.app.mysql.get('user', { phone: mobile });
    // console.log(result);
    return this._userPublicInfo(result);
  }

  async findByAccount(_id) {
    const result = await this.app.mysql.get('user', { account: _id });
    return result;
  }

  async findPublicbyAccount(_id) {
    const result = await this.app.mysql.get('user', { account: _id });
    return this._userPublicInfo(result);
  }
  async getRolpic() {
    // 假如 我们拿到用户 id 从数据库获取用户详细信息
    const rolpic = await this.app.mysql.select('rollingpic', {
      where: { ava: 1 },
    });
    return rolpic;
  }

  async getPicture(uid) {
    const result = await this.ctx.curl(`http://photoserver/uid=${uid}`, { dataType: 'json' });
    return result.data;
  }

  async editinfo(_id, info){
    console.log('info',info);
    const options = {
      where: {
        account: _id
      }
    }
    const result = await this.app.mysql.update('user',info,options);
    return result;
  }

  async register(params){
    let res;
    const newphone = params.phone;
    console.log("newphone",newphone);
    const isexist = await this.app.mysql.select('user',{
      where: { phone: newphone }
    });
    console.log("isexist",isexist.length);
    if (isexist.length !== 0) {
      return {'isexist': true};
    } else {
       res = await this.app.mysql.insert('user', params);
    }
    return res;
  }
}
module.exports = UserService;
